package q463;

/**
 * 463. 岛屿的周长
 */
public class Solution {

    int perimeter = 0;

    public int islandPerimeter(int[][] grid) {
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == 1) {
                    dfs(grid, i, j);
                    break;
                }
            }
        }

        return perimeter;
    }

    public void dfs(int[][] grid, int row, int col) {
        if (!judgePass(grid, row, col)) return;
        grid[row][col] = 2;
        dfs(grid, row - 1, col);
        dfs(grid, row + 1, col);
        dfs(grid, row, col - 1);
        dfs(grid, row, col + 1);
        // 上面是否是边
        if (row == 0 || grid[row - 1][col] == 0) perimeter++;
        // 下边是否是边
        if (row == grid.length - 1 || grid[row + 1][col] == 0) perimeter++;
        // 左边是否是边
        if (col == 0 || grid[row][col - 1] == 0) perimeter++;
        // 右边是否是边
        if (col == grid[0].length - 1 || grid[row][col + 1] == 0) perimeter++;
    }

    // 校验此节点是是否是陆地并且没有经过
    public boolean judgePass(int[][] grid, int i, int j) {
        return i >= 0 && i < grid.length && j >= 0 && j < grid[0].length && grid[i][j] == 1;
    }

    public static void main(String[] args) {
        int[][] grid = new int[][]{{0, 1}};
        Solution solution = new Solution();
        System.out.println(solution.islandPerimeter(grid));
    }
}
